package com.taotao.manage.controller;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.taotao.manage.pojo.ItemCat;
import com.taotao.manage.pojo.ItemCatVO;
import com.taotao.manage.service.ItemCatService;

@RequestMapping("item/cat")
@Controller
public class ItemCatController {
	
	@Autowired
	private ItemCatService itemCatService;

	/**
	 * 根据parentId查询所有子类目
	 * @param parentId
	 * @return
	 */
	@GetMapping
	public ResponseEntity<List<ItemCatVO>> queryItemCatList(@RequestParam(value="id", defaultValue="0")Long parentId){
		
		try {
			ItemCat record = new ItemCat();
			record.setParentId(parentId);
			record.setStatus(1);
			List<ItemCat> itemCatList = this.itemCatService.queryListByWhere(record);
			List<ItemCatVO> itemCatVOList = new ArrayList<>();
			for (ItemCat itemCat: itemCatList) {
				ItemCatVO itemCatVO = new ItemCatVO();
				BeanUtils.copyProperties(itemCatVO, itemCat);
				itemCatVOList.add(itemCatVO);
			}
			if(CollectionUtils.isEmpty(itemCatList)){
				return ResponseEntity.notFound().build();
			}
			return ResponseEntity.ok(itemCatVOList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
	}
	
	/**
	 * 根据id查询商品类目
	 * @param id
	 * @return
	 */
	@GetMapping("{id}")
	public ResponseEntity<ItemCat> queryItemCatById(@PathVariable("id")Long id){
		try {
			// 如果参数不合法，响应400
			if(id == null || id.longValue() <= 0){
				return ResponseEntity.badRequest().build();
			}
			// 查询商品描述
			ItemCat itemCat = this.itemCatService.queryById(id);
			if(itemCat == null){
				// 响应404
				return ResponseEntity.notFound().build();
			}
			// 响应200
			return ResponseEntity.ok(itemCat);
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 响应500
		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
	}
	
	
}
